package com.mh.shiro.controller;

import com.mh.shiro.business.entity.Resources;
import com.mh.shiro.business.entity.User;
import com.mh.shiro.business.service.SysResourcesService;
import com.mh.shiro.framework.object.ResponseVO;
import com.mh.shiro.persistence.beans.SysResources;
import com.mh.shiro.util.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: E-mail:
 * @Version: 创建时间：2019年06月20日15:19
 * @Description: 登录相关
 */
@Slf4j
@Controller
@RequestMapping(value = "/passport")
public class PassportController {

    @Autowired
    private SysResourcesService resourcesService;

    @GetMapping("/login")
    public ModelAndView login(Model model) {

        return ResultUtil.view("/login");
    }

    /**
     * 加载菜单资源
     * @return
     */
    @ModelAttribute("resources")
    public List<Resources> loadResources() {

        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");

        Map<String,Object> map = new HashMap<>();
        map.put("type","menu");
        map.put("userId",user.getId());

        List<Resources> resources = resourcesService.listUserResources(map);

        System.out.println("============"+resources);

        return resources;
    }

    /**
     * 账号和密码登录
     *
     * @param username
     * @param password
     * @param rememberMe
     * @param kaptcha
     * @return
     */
    @PostMapping("/signin")
    @ResponseBody
    public ResponseVO submitLogin(String username, String password, boolean rememberMe, String kaptcha) {

        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        //获取当前的Subject
        Subject currentUser = SecurityUtils.getSubject();

        try {
            //再调用了login方法后，SecrityManager会收到AuthenitcationToken，并将其发送给已配置的Realm执行必须的认证检查
            //每个Realm都能在必要时对提交的AuthenticationToken作出反应
            //所有这一步在调用login(token)方法时，它会走到xxRealm.doGetAuthenticationInfo()方法中，具体验证方式详见此方法
            currentUser.login(token);

            return ResultUtil.success("登录成功！");
        } catch (Exception e) {
            log.error("登录失败，用户名[{}}", username, e);
            token.clear();
            return ResultUtil.error(e.getMessage());
        }
    }

    /**
     * 使用权限管理工具进行用户的退出，调出登录，给出提示信息
     *
     * @param redirectAttributes
     * @return
     */
    @RequestMapping("/logout")
    public ModelAndView logout(RedirectAttributes redirectAttributes) {

        redirectAttributes.addFlashAttribute("message", "您已安全退出");
        return ResultUtil.redirect("index");
    }

}
